<template>
  <div>
  <div style="display: flex; margin-top: 10px; justify-content: space-between; margin-left: 1%; margin-right: 1%">
    <div v-for="(item, index) in topFive"
         :key="index"
         style="background: linear-gradient(to right,deepskyblue,blueviolet); height: 100px; width: 200px;
         border: 1px solid grey; border-radius: 10px; display: flex; flex-direction: column;
         justify-content: center; align-items: center; color: white" >
      {{item.title}}
      <div>{{item.amount}}{{item.suffix}}</div>
      <div>环比增长
        <label for="" style="color: orangered">{{item.growth}}</label>
        %</div>
    </div>
  </div>

  <div style="display: flex; margin-top: 10px; justify-content: space-between; margin-left: 1%; margin-right: 1%; height: 280px">
    <div>
      <e-charts class="chart1" :option="option1"/>
    </div>
    <div>
      <e-charts class="chart1" :option="option2"/>
    </div>
    <div>
      <e-charts class="chart1" :option="option3"/>
    </div>
  </div>
  <div style="display: flex; margin-top: 10px; justify-content: space-between; margin-left: 1%; margin-right: 1%; height: 280px">
    <div>
      <e-charts class="chart1" :option="option4"/>
    </div>
    <div>
      <e-charts class="chart1" :option="option5"/>
    </div>
    <div>
      <e-charts class="chart1" :option="option6"/>
    </div>
  </div>
  <div style="display: flex; margin-top: 10px; justify-content: space-between; margin-left: 1%;
  margin-right: 1%; height: 280px">
    <div>
      <e-charts class="chart1" :option="option7"/>
    </div>
    <div style="width: 65%;">
      <el-table :data="tableData" style="width: 100%; border: 2px solid antiquewhite; border-radius: 10px" height="280" title="今日充电订单">
        <el-table-column fixed prop="订单号" label="订单号" width="150" />
        <el-table-column prop="订单金额" label="订单金额" width="120" />
        <el-table-column prop="电量" label="电量" width="120" />
        <el-table-column prop="订单时间" label="订单时间" width="220" />
        <el-table-column prop="充电站" label="充电站" width="600" />
<!--        <el-table-column prop="zip" label="Zip" />-->
<!--        <el-table-column v-for="(item, index) in tableData" :key="index" prop="item." label="订单号" />-->
      </el-table>
  </div>
  </div>
  </div>
</template>

<script setup name="Index">

import { todayOrder,todayCountOrder,yesterdayOrder,yesterdayCountOrder
  ,weekOrder,weekCountOrder,lastWeekOrder,lastWeekCountOrder,weekRechargeAmountOrder,
  lastWeekRechargeAmountOrder,todayRegisterCount,weekRegisterCount,lastWeekRegisterCount,
  typePercentageOrder,todayAllOrder, yesterdayRegisterCount} from "@/api/system/order"
import ECharts from "vue-echarts";
import { listStation, selectTodayStationCharge } from "@/api/system/station"
import {selectTodayRechargeAmount, selectYesterdayRechargeAmount} from "@/api/system/huiyuan"
import { ElTable } from 'element-plus'

//今日充电度数
const todayAmount = ref(0)
const topFive = ref([
  {
    title: '今日充电度数',
    amount: 0.00,
    growth: null,
    suffix: '度'
  },
  {
    title: '今日充电金额',
    amount: 0.00,
    growth: null,
    suffix: '元'
  },
  {
    title: '今日充值金额',
    amount: 0.00,
    growth: null,
    suffix: '元'
  },
  {
    title: '今日充电次数',
    amount: 0,
    growth: null,
    suffix: '次'
  },
  {
    title: '今日注册用户数',
    amount: 0,
    growth: null,
    suffix: '人'
  },
])
// const list = ['今日充电度数', '今日充电金额', '今日充值金额', '今日充电次数', '今日注册用户数']
// 本周每日充电度数
const weekAmountData = ref([])
// 上周每日充电度数
const lastWeekAmountData = ref([])
// 本周每日充电金额
const weekData = ref([])
// 上周每日充电金额
const lastWeekData = ref([])
// 本周每日充值金额
const weekRechargeAmountData = ref([])
// 上周每日充值金额
const lastWeekRechargeAmountData = ref([])
// 本周每日充电次数
const weekCountData = ref([])
// 上周每日充电次数
const lastWeekCountData = ref([])
// 本周注册人数
const weekRegisterCountData = ref([])
// 上周注册人数
const lastWeekRegisterCountData = ref([])
// 所有充电站
const stations = ref([])
// 今日充电站充电度数
const stationCharge = ref([])
// 支付方式占比
const typePercentage = ref([])
// 今日充电订单
const tableData = ref([])
const version = ref('3.9.0')
const weekend = ref(['周一', '周二', '周三', '周四', '周五', '周六', '周日'])
const option1 = ref({
  title: {
    text: '本周充电度数',

  },
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['上周', '本周']
  },
  toolbox: {
    show: true,
    feature: {
      dataView: { show: true, readOnly: false },
      magicType: { show: true, type: ['line', 'bar'] },
      restore: { show: true },
      saveAsImage: { show: true }
    }
  },
  calculable: true,
  xAxis: [
    {
      type: 'category',
      // prettier-ignore
      data: weekend.value
    }
  ],
  yAxis: [
    {
      type: 'value'
    }
  ],
  series: [
    {
      name: '上周',
      type: 'bar',
      data: lastWeekAmountData.value,
      markPoint: {
        data: [
          { type: 'max', name: 'Max' },
          { type: 'min', name: 'Min' }
        ]
      },
      markLine: {
        data: [{ type: 'average', name: 'Avg' }]
      }
    },
    {
      name: '本周',
      type: 'bar',
      data: weekAmountData.value,
      markPoint: {
        data: [
          { name: 'Max', value: 182.2, xAxis: 7, yAxis: 183 },
          { name: 'Min', value: 2.3, xAxis: 11, yAxis: 3 }
        ]
      },
      markLine: {
        data: [{ type: 'average', name: 'Avg' }]
      }
    }
  ]
});
const option2 = ref({
  title: {
    text: '本周充电金额',

  },
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['上周', '本周']
  },
  toolbox: {
    show: true,
    feature: {
      dataView: { show: true, readOnly: false },
      magicType: { show: true, type: ['line', 'bar'] },
      restore: { show: true },
      saveAsImage: { show: true }
    }
  },
  calculable: true,
  xAxis: [
    {
      type: 'category',
      // prettier-ignore
      data: weekend.value
    }
  ],
  yAxis: [
    {
      type: 'value'
    }
  ],
  series: [
    {
      name: '上周',
      type: 'line',
      data: lastWeekData.value,
      markPoint: {
        data: [
          { type: 'max', name: 'Max' },
          { type: 'min', name: 'Min' }
        ]
      },
      markLine: {
        data: [{ type: 'average', name: 'Avg' }]
      }
    },
    {
      name: '本周',
      type: 'line',
      data: weekData.value,
      markPoint: {
        data: [
          { name: 'Max', value: 182.2, xAxis: 7, yAxis: 183 },
          { name: 'Min', value: 2.3, xAxis: 11, yAxis: 3 }
        ]
      },
      markLine: {
        data: [{ type: 'average', name: 'Avg' }]
      }
    }
  ]
});
const option3 = ref({
  title: {
    text: '本周充电次数',

  },
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['上周', '本周']
  },
  toolbox: {
    show: true,
    feature: {
      dataView: { show: true, readOnly: false },
      magicType: { show: true, type: ['line', 'bar'] },
      restore: { show: true },
      saveAsImage: { show: true }
    }
  },
  calculable: true,
  xAxis: [
    {
      type: 'category',
      // prettier-ignore
      data: weekend.value
    }
  ],
  yAxis: [
    {
      type: 'value',
      name: '本周',
      axisLabel: {
        formatter: '{value}'
      }
    },
    {
      type: 'value',
      name: '上周',
      axisLabel: {
        formatter: '{value}'
      }
    }
  ],
  series: [
    {
      name: '上周',
      type: 'bar',
      tooltip: {
        valueFormatter: function (value) {
          return value + ' 次';
        }
      },
      data: lastWeekCountData.value,

    },
    {
      name: '本周',
      type: 'line',
      tooltip: {
        valueFormatter: function (value) {
          return value + ' 次';
        }
      },
      yAxisIndex: 1,
      data: weekCountData.value,

    }
  ]
});
const option4 = ref({
  title: {
    text: '本周充值金额',
  },
  legend: {
    data: ['上周', '本周']
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: weekend.value
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '上周',
      data: weekRechargeAmountData.value,
      type: 'line',
      areaStyle: {}
    },
    {
      name: '本周',
      data: lastWeekRechargeAmountData.value,
      type: 'line',
      areaStyle: {}
    }
  ]
});

const emphasisStyle = {
  itemStyle: {
    shadowBlur: 10,
    shadowColor: 'rgba(0,0,0,0.3)'
  }
};
const option5 = ref({
  title: {
    text: '本周注册用户数量',
  },
  legend: {
    data: ['上周', '本周'],
    left: '50%'
  },

  toolbox: {
    feature: {
      magicType: {
        type: ['stack']
      },
      dataView: {}
    }
  },
  tooltip: {},
  xAxis: {
    data: weekend.value,
    axisLine: { onZero: true },
    splitLine: { show: false },
    splitArea: { show: false }
  },
  yAxis: {},
  grid: {
    bottom: 65
  },
  series: [
    {
      name: '上周',
      type: 'bar',
      stack: 'one',
      emphasis: emphasisStyle,
      data: lastWeekRegisterCountData.value
    },
    {
      name: '本周',
      type: 'bar',
      stack: 'one',
      emphasis: emphasisStyle,
      data: weekRegisterCountData.value
    },
  ]
});
const option6 = ref({
  title: {
    text: '今日各充电站充电度数'
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  legend: {},
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'value',
    boundaryGap: [0, 0.01]
  },
  yAxis: {
    type: 'category',
    data: stations
  },
  series: [
    {
      type: 'bar',
      data: stationCharge
    },
  ]
});
const option7 = ref({
  tooltip: {
    trigger: 'item'
  },
  legend: {
    top: '5%',
    left: 'center'
  },
  series: [
    {
      name: 'Access From',
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 40,
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: typePercentage
    }
  ]
});

onMounted(() => {
  initData()
  getTodayOrder()
  getTodayCountOrder()
  getWeekOrder()
  getLastWeekOrder()
  getWeekCountOrder()
  getLastWeekCountOrder()
  getWeekRechargeAmountOrder()
  getLastWeekRechargeAmountOrder()
  getTodayCountOrder()
  getWeekRegisterCount()
  getLastWeekRegisterCount()
  getStations()
  getTodayStationCharge()
  getTypePercentage()
  getTodayRegisterCount()
  getTodayAllOrder()
  getYesterdayRegisterCount()
  getTodayRechargeAmount()
  getYesterdayRechargeAmount()
  getYesterdayOrder()
  getYesterdayCountOrder()
})
function getTodayOrder() {
  todayOrder().then(response => {
    if (response){
      topFive.value[0].amount = response
      console.log(response);
      topFive.value[1].amount = (response * 1.2).toFixed(2)
    }
  })
}

function getTodayCountOrder() {
  todayCountOrder().then(response => {
    if (response){
      topFive.value[3].amount = response
    }
  })
}

function getYesterdayOrder() {
  yesterdayOrder().then(response => {
    topFive.value[0].growth = ((topFive.value[0].amount - response) / response).toFixed(4) * 100
    console.log(response);
    console.log(topFive.value[0].amount);
    topFive.value[1].growth = topFive.value[0].growth
  })
}

function getYesterdayCountOrder() {
  yesterdayCountOrder().then(response => {
    topFive.value[3].growth = (topFive.value[3].amount - response) / response * 100
  })
}

function getWeekOrder() {
  weekOrder().then(response => {
    // 创建响应数据的映射表（提高查找效率）
    const responseMap = {};
    response.forEach(item => {
      responseMap[item.weekName] = item.dailyAmount;
    });

    // 按weekend.value的顺序填充数据
    weekend.value.forEach(day => {
      weekAmountData.value.push(responseMap[day] || 0);
      weekData.value.push((responseMap[day] * 1.2).toFixed(2) || 0)
    });
  }).catch(error => {
    console.error('获取周数据失败:', error);
    // 可以设置默认值或显示错误信息
    weekAmountData.value = Array(7).fill(0);
  });
}

function getLastWeekOrder() {
  lastWeekOrder().then(response => {
    // 创建响应数据的映射表（提高查找效率）
    const responseMap = {};
    response.forEach(item => {
      responseMap[item.weekName] = item.dailyAmount;
    });

    // 按weekend.value的顺序填充数据
    weekend.value.forEach(day => {
      lastWeekAmountData.value.push(responseMap[day] || 0);
      lastWeekData.value.push((responseMap[day] * 1.2).toFixed(2) || 0);
    });
  }).catch(error => {
    console.error('获取周数据失败:', error);
    // 可以设置默认值或显示错误信息
    lastWeekAmountData.value = Array(7).fill(0);
  })
}

function getWeekCountOrder() {
  weekCountOrder().then(response => {
    // 创建响应数据的映射表（提高查找效率）
    const responseMap = {};
    response.forEach(item => {
      responseMap[item.weekName] = item.dailyCount;
    });

    // 按weekend.value的顺序填充数据
    weekend.value.forEach(day => {
      weekCountData.value.push(responseMap[day] || 0);
    });
  }).catch(error => {
    console.error('获取周数据失败:', error);
    // 可以设置默认值或显示错误信息
    weekCountData.value = Array(7).fill(0);
  })
}
function getLastWeekCountOrder() {
  lastWeekCountOrder().then(response => {
    // 创建响应数据的映射表（提高查找效率）
    const responseMap = {};
    response.forEach(item => {
      responseMap[item.weekName] = item.dailyCount;
    });

    // 按weekend.value的顺序填充数据
    weekend.value.forEach(day => {
      lastWeekCountData.value.push(responseMap[day] || 0);
    });
  }).catch(error => {
    console.error('获取周数据失败:', error);
    // 可以设置默认值或显示错误信息
    lastWeekCountData.value = Array(7).fill(0);
  })
}

function getWeekRechargeAmountOrder() {
  weekRechargeAmountOrder().then(response => {
    // 创建响应数据的映射表（提高查找效率）
    const responseMap = {};
    response.forEach(item => {
      responseMap[item.weekName] = item.dailyRechargeAmount;
    });

    // 按weekend.value的顺序填充数据
    weekend.value.forEach(day => {
      weekRechargeAmountData.value.push(responseMap[day] || 0);
    });
  }).catch(error => {
    console.error('获取周数据失败:', error);
    // 可以设置默认值或显示错误信息
    weekRechargeAmountData.value = Array(7).fill(0);
  })
}

function getLastWeekRechargeAmountOrder() {
  lastWeekRechargeAmountOrder().then(response => {
    // 创建响应数据的映射表（提高查找效率）
    const responseMap = {};
    response.forEach(item => {
      responseMap[item.weekName] = item.dailyRechargeAmount;
    });

    // 按weekend.value的顺序填充数据
    weekend.value.forEach(day => {
      lastWeekRechargeAmountData.value.push(responseMap[day] || 0);
    });
  }).catch(error => {
    console.error('获取周数据失败:', error);
    // 可以设置默认值或显示错误信息
    lastWeekRechargeAmountData.value = Array(7).fill(0);
  })
}

function getWeekRegisterCount() {
  weekRegisterCount().then(response => {
    // 创建响应数据的映射表（提高查找效率）
    const responseMap = {};
    response.forEach(item => {
      responseMap[item.weekName] = item.dailyRegisterCount;
    });

    // 按weekend.value的顺序填充数据
    weekend.value.forEach(day => {
      weekRegisterCountData.value.push(responseMap[day] || 0);
    });
  }).catch(error => {
    console.error('获取周数据失败:', error);
    // 可以设置默认值或显示错误信息
    weekRegisterCountData.value = Array(7).fill(0);
  })
}

function getLastWeekRegisterCount() {
  lastWeekRegisterCount().then(response => {
    // 创建响应数据的映射表（提高查找效率）
    const responseMap = {};
    response.forEach(item => {
      responseMap[item.weekName] = item.dailyRegisterCount;
    });

    // 按weekend.value的顺序填充数据
    weekend.value.forEach(day => {
      lastWeekRegisterCountData.value.push(responseMap[day] || 0);
    });
  }).catch(error => {
    console.error('获取周数据失败:', error);
    // 可以设置默认值或显示错误信息
    lastWeekRegisterCountData.value = Array(7).fill(0);
  })
}

async function initData() {
  await getStations(); // 先获取充电站列表
  await getTodayStationCharge(); // 再获取充电数据
}

// 修改后的函数
async function getStations() {
  const res = await listStation();
  stations.value = res.rows.map(item => item.csName);
  // console.log('充电站列表:', stations.value); // 确保这里能打印
}

async function getTodayStationCharge() {
  try {
    // 1. 清空旧数据
    stationCharge.value = [];

    // 2. 获取API数据
    const response = await selectTodayStationCharge();
    const chargeMap = response.reduce((map, item) => {
      map[item.cs_name] = item.station_charge || 0;
      return map;
    }, {});

    // 3. 填充数据（确保与stations顺序一致）
    stationCharge.value = stations.value.map(name => chargeMap[name] ?? 0);

    // 4. 调试输出（使用深层拷贝避免Proxy影响）
    // console.log('充电站列表:', [...stations.value]);
    // console.log('充电量数据:', [...stationCharge.value]);

  } catch (error) {
    console.error('获取充电数据失败:', error);
    stationCharge.value = Array(stations.value.length).fill(0);
  }
}

function getTypePercentage() {
  typePercentageOrder().then(response => {
    typePercentage.value = response;
  })
}

function getTodayRegisterCount() {
  todayRegisterCount().then(response => {
    topFive.value[4].amount = response;
  })
}

function getYesterdayRegisterCount() {
  yesterdayRegisterCount().then(response => {
    if (response){
      topFive.value[4].growth = (topFive.value[4].amount - response) / response * 100;
    }else {
      topFive.value[4].growth = 0;
    }

  })
}

function getTodayAllOrder() {
  todayAllOrder().then(response => {
    tableData.value = response;
    console.log('table：'+tableData.value);
    console.log(response)
  })
}

function getTodayRechargeAmount() {
  selectTodayRechargeAmount().then(response => {
    topFive.value[2].amount = response;
  })
}

function getYesterdayRechargeAmount() {
  selectYesterdayRechargeAmount().then(response => {
    topFive.value[2].growth = (topFive.value[2].amount - response) / response * 100;
  })
}


function goTarget(url) {
  window.open(url, '__blank')
}
</script>

<style scoped lang="scss">
.chart1 {
  height: 100%;
  width: 380px;
  border: 2px solid antiquewhite;
  padding: 10px;
  border-radius: 10px;
}
.chart2 {
  height: 100%;
  width: 770px;
  border: 2px solid antiquewhite;
  padding: 10px;
  border-radius: 10px;

}

</style>

